package servlets;

import model.Person;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExportServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Person person1 = new Person();
        person1.setIdCardNumber("1234567890123456789");
        person1.setName("张小山");
        person1.setUsedName("张三");
        person1.setNativeplace("新疆乌鲁木齐市天山区");
        Person person2 = new Person();
        person2.setIdCardNumber("0987654321098765432");
        person2.setName("李小斯");
        person2.setUsedName("李四");
        person2.setNativeplace("新疆乌鲁木齐市米东区");

        List<Person> persons = new ArrayList<>();
        persons.add(person1);
        persons.add(person2);

        String reportFilePath = request.getServletContext().getRealPath("/reports/Person.jasper");
        Map<String, Object> parameters = new HashMap<>();

        try {
            JasperPrint jasperPrint = JasperFillManager.fillReport(reportFilePath, parameters, new JRBeanCollectionDataSource(persons));
            request.getSession().setAttribute(BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);

            String type = request.getParameter("type");
            if (type == null) {
                type = "html";
            }
            switch (type) {
                case "pdf":
                    request.getRequestDispatcher("/servlets/pdf").forward(request, response);
                    break;
                case "xls":
                    request.getRequestDispatcher("/servlets/xls").forward(request, response);
                    break;
                case "xlsx":
                    request.getRequestDispatcher("/servlets/xlsx").forward(request, response);
                    break;
                case "docx":
                    request.getRequestDispatcher("/servlets/docx").forward(request, response);
                    break;
                case "html":
                default:
                    request.getRequestDispatcher("/servlets/html").forward(request, response);
                    break;
            }
        } catch (JRException e) {
            e.printStackTrace();
        }
    }
}
